package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import com.sanqing.model.NumberListener;
import com.sanqing.model.PopupMenu;
import com.sanqing.model.*;
import com.sanqing.dao.Dao;
import com.sanqing.model.*;

public class NewBookcheckFrame extends JInternalFrame {

    private String isbn;
    private Integer bookType;
    private String bookNames;
    private String writers;
    private String translators;
    private String publishers;
    private String languages;
    private String recommend;
    private String recommender;
    private Double price; // 新增：价格变量
    private String[] columnNames;
    private Date CurrentDate;
    private JTextField number; // 库存数量文本框
    private JTextField priceField; // 新增：价格文本框
    private JTable table;
    private Item item;
    private PopupMenu popupMenu;
    private boolean isNewRecord = false;

    private Object[][] getFileStates(List list) {
        String[] columnNames = { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "语言", "出版日期","推荐人","推荐理由" }; // 新增：价格列
        Object[][] results = new Object[list.size()][columnNames.length];
        for (int i = 0; i < list.size(); i++) {
            OrderInfo orderinfo = (OrderInfo) list.get(i);
            results[i][0] = orderinfo.getISBN();
            Integer typeId = orderinfo.getTypeid();
            String bookTypeName = MapPz.getIdToName().get(typeId);
            results[i][1] = bookTypeName;
            results[i][2] = orderinfo.getBookname();
            results[i][3] = orderinfo.getWriter();
            results[i][4] = orderinfo.getTranslator();
            results[i][5] = orderinfo.getPublisher();
            results[i][6] = orderinfo.getLanguage();
            results[i][7] = orderinfo.getDate();
            results[i][8] = orderinfo.getRecommender(); // 推荐理由
            results[i][9] = orderinfo.getReason(); // 推荐理由
        }
        return results;
    }

    public NewBookcheckFrame() {
        super();
        final BorderLayout borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);
        setIconifiable(true);
        setClosable(true);
        setTitle("新书验收");
        setBounds(20, 100, 850, 400);
        final JPanel mainPanel = new JPanel();
        final BorderLayout borderLayout_1 = new BorderLayout();
        borderLayout_1.setVgap(5);
        mainPanel.setLayout(borderLayout_1);
        mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        getContentPane().add(mainPanel);
        final JScrollPane scrollPane = new JScrollPane();
        mainPanel.add(scrollPane);

        Object[][] results = getFileStates(Dao.selectOrderInfo());
        columnNames = new String[] { "图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "语言", "出版日期","推荐人", "推荐理由" };
        table = new JTable(results, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 所有单元格都不可编辑
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // 使用PopupMenu中的TableListener
        popupMenu = new PopupMenu(table, this, columnNames);
        table.addMouseListener(new CombinedTableListener());
        scrollPane.setViewportView(table);

        // 添加输入面板（数量和价格）
        final JPanel inputPanel = new JPanel();
        final GridLayout gridLayout = new GridLayout(1, 4); // 改为4列布局
        gridLayout.setHgap(10);
        inputPanel.setLayout(gridLayout);
        inputPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
        mainPanel.add(inputPanel, BorderLayout.SOUTH);

        // 数量标签和文本框
        final JLabel numberLabel = new JLabel("数量:", SwingConstants.RIGHT);
        inputPanel.add(numberLabel);
        number = new JTextField(10);
        number.addKeyListener(new NumberListener()); // 整数输入监听
        inputPanel.add(number);

        // 价格标签和文本框
        final JLabel priceLabel = new JLabel("价格:", SwingConstants.RIGHT);
        inputPanel.add(priceLabel);
        priceField = new JTextField(10);
        priceField.addKeyListener(new FloatNumberListener()); // 浮点数输入监听
        inputPanel.add(priceField);

        // 底部按钮
        final JPanel bottomPanel = new JPanel();
        bottomPanel.setBorder(new LineBorder(new java.awt.Color(139, 137, 137), 1, false));
        getContentPane().add(bottomPanel, BorderLayout.SOUTH);

        final FlowLayout flowLayout = new FlowLayout(FlowLayout.RIGHT, 30, 2);
        bottomPanel.setLayout(flowLayout);

        final JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new DeleteBookActionListener());
        bottomPanel.add(deleteButton);
        
        final JButton addToRecordButton = new JButton("验收");
        addToRecordButton.addActionListener(new AddToRecordActionListener());
        bottomPanel.add(addToRecordButton);
        
        final JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> doDefaultCloseAction());
        bottomPanel.add(closeButton);
        
        // 头部图标
        final JLabel headLogo = new JLabel();
        ImageIcon bookModiAndDelIcon = new ImageIcon("res/login.jpg");
        headLogo.setIcon(bookModiAndDelIcon);
        headLogo.setOpaque(true);
        headLogo.setBackground(new java.awt.Color(173, 216, 230));
        headLogo.setPreferredSize(new Dimension(400, 80));
        headLogo.setBorder(new LineBorder(new java.awt.Color(139, 137, 137), 1, false));
        getContentPane().add(headLogo, BorderLayout.NORTH);
        
        // 新增：添加窗体焦点监听
        addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                refreshTable(); // 窗体获得焦点时刷新表格
            }
        });
        setVisible(true);
    }

    // 组合鼠标监听器
    private class CombinedTableListener extends MouseAdapter {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {
                int selRow = table.getSelectedRow();
                if (selRow < 0) return;

                isbn = table.getValueAt(selRow, 0).toString().trim();
                bookType = MapPz.getNameToId().get(table.getValueAt(selRow, 1).toString().trim());
                bookNames = table.getValueAt(selRow, 2).toString().trim();
                writers = table.getValueAt(selRow, 3).toString().trim();
                translators = table.getValueAt(selRow, 4).toString().trim();
                publishers = table.getValueAt(selRow, 5).toString().trim();
                languages = table.getValueAt(selRow, 6).toString().trim();
                recommender = table.getValueAt(selRow, 8).toString().trim();
                recommend = table.getValueAt(selRow, 9).toString().trim();

                // 自动填充数量和价格文本框
                number.setText("1"); // 默认为1
            }
            // 调用PopupMenu中的TableListener处理右击事件
            else popupMenu.getTableListener().mouseClicked(e);
        }
    }

    public class DeleteBookActionListener implements ActionListener {
        public void actionPerformed(final ActionEvent e) {
            if (isbn == null || isbn.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请先选择要删除的图书");
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(null, "确定要删除ISBN为 " + isbn + " 的图书吗？", 
                                                       "删除确认", JOptionPane.YES_NO_OPTION);
            if (confirm != JOptionPane.YES_OPTION) return;

            // 执行删除
            int deleteResult = Dao.Deleteorder(isbn);

            if (deleteResult == 1) {
                JOptionPane.showMessageDialog(null, "删除成功");
                refreshTable();
            } else {
                JOptionPane.showMessageDialog(null, "删除失败，请检查数据");
            }
        }
    }
    
    public class AddToRecordActionListener implements ActionListener {
        public void actionPerformed(final ActionEvent e) {
            if (isbn == null || isbn.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请先选择图书");
                return;
            }
            
            // 数量校验
            String numStr = number.getText().trim();
            if (numStr.isEmpty()) {
                JOptionPane.showMessageDialog(null, "库存数量不能为空");
                return;
            }
            Integer num;
            try {
                num = Integer.parseInt(numStr);
                if (num <= 0) {
                    JOptionPane.showMessageDialog(null, "库存数量必须为正整数");
                    return;
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "库存数量格式不正确，请输入整数");
                return;
            }
            
            // 价格校验
            String priceStr = priceField.getText().trim();
            if (priceStr.isEmpty()) {
                JOptionPane.showMessageDialog(null, "价格不能为空");
                return;
            }
            Double price;
            try {
                price = Double.parseDouble(priceStr);
                if (price <= 0) {
                    JOptionPane.showMessageDialog(null, "价格必须为正浮点数");
                    return;
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "价格格式不正确，请输入数字（允许一个小数点）");
                return;
            }
            
            // 获取当前日期
            LocalDate local = LocalDate.now();
            CurrentDate = Date.valueOf(local);
            
            // 执行添加到记录和图书表
            int addRecordResult = Dao.Insertrecord(
                    isbn,
                    bookType,
                    bookNames,
                    writers,
                    translators,
                    publishers,
                    languages,
                    CurrentDate,
                    recommend,
                    price,
                    num,
                    common.UserName
            );
            
            if (addRecordResult == 1) {
                JOptionPane.showMessageDialog(null, "验收成功");
                // 添加到书籍表中
                int addBookResult = Dao.Insertbook(
                        isbn,
                        bookType,
                        bookNames,
                        writers,
                        translators,
                        publishers,
                        languages,
                        CurrentDate,
                        price,
                        num
                );
                if(addBookResult!=1)   JOptionPane .showMessageDialog(null, "添加书籍失败，请检查数据");
                // 添加推荐信息，判断是否是读者推荐的
                if(!recommender.equals("NULL"))
                {
                    int addRecommenderResult=Dao.InsertRecommender(recommender, isbn); 
                    if(addRecommenderResult!=1)  JOptionPane.showMessageDialog(null, "添加推荐信息失败，请检查数据");
                }
                
                // 删除订单记录
                int deleteResult = Dao.Deleteorder(isbn);
                if (deleteResult != 1) {
                    JOptionPane.showMessageDialog(null, "删除订单失败，请检查数据");
                } 
                refreshTable();
            } else {
                JOptionPane.showMessageDialog(null, "验收失败，请检查数据");
            }
        }
    }
    
    // 刷新表格
    private void refreshTable() {
        Object[][] results = getFileStates(Dao.selectOrderInfo());
        DefaultTableModel model = new DefaultTableModel(results, columnNames);
        table.setModel(model);
    }
}